<template>
  <div class="body">
    <div class="content">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-row>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="ruleForm.name" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="ruleForm.username" @blur="checkUsername(ruleForm.username)"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="ruleForm.password" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="头像" prop="photo">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8081/common/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="ruleForm.gender">
            <el-radio label="男" name="男" />
            <el-radio label="女" name="女" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="ruleForm.birthday"
          >
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-row>
          <el-form-item label="手机" prop="phone">
            <el-input v-model="ruleForm.phone" @blur="checkPhone(ruleForm.phone)"/>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="省" prop="sheng">
              <el-select v-model="ruleForm.sheng" placeholder="请选择省" @change="getCity">
                <el-option v-for="item in province" :key="item.cid" :label="item.cname" :value="item.cid" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="市" prop="shi">
              <el-select v-model="ruleForm.shi" placeholder="请选择市" @change="getPrefecture">
                <el-option v-for="item in city" :key="item.cid" :label="item.cname" :value="item.cid" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="区" prop="qu">
          <el-select v-model="ruleForm.qu" placeholder="请选择区">
            <el-option v-for="item in prefecture" :key="item.cid" :label="item.cname" :value="item.cid" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-row>
            <el-col :span="12">
              <el-button type="primary" @click="submitForm('ruleForm')">注册</el-button>
            </el-col>
            <el-col :span="12" :push="9">
              <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { getAction, postAction } from '@/utils/xhs-ajax'
import { lo } from 'pinyin/data/dict-zi-web'
import item from '@/layout/components/Sidebar/Item.vue'

export default {
  name: 'Register',
  data() {
    return {
      isUsername: false,
      isPhone: false,
      ruleForm: {
        name: '',
        username: '',
        password: '',
        photo: '',
        gender: '男',
        birthday: null,
        sheng: 22,
        shi: 283,
        qu: 2333,
        phone: null
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ],
        sheng: [
          { required: true, message: '请选择省', trigger: 'change' }
        ],
        shi: [
          { required: true, message: '请选择市', trigger: 'change' }
        ],
        qu: [
          { required: true, message: '请选择区', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请填写家庭住址', trigger: 'blur' }
        ]
      },
      imageUrl: '',
      province: [], // 省份
      city: [], // 城市
      prefecture: [] // 地区
    }
  },
  computed: {
    item() {
      return item
    }
  },
  created() {
    this.getProvince()
  },
  methods: {
    checkUsername(username) { // 查找用户名是否重复
      getAction('/user/checkUsername.do?username=' + username).then(resp => {
        this.isUsername = resp.isSuccess
      })
    },
    checkPhone(phone) { // 查找手机号是否重复
      getAction('/user/checkPhone.do?phone=' + phone).then(resp => {
        this.isPhone = resp.isSuccess
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.register()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.getProvince()
    },
    // 头像上传处理方法
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.ruleForm.photo = this.imageUrl
    },
    // 上传头像前置方法
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    getProvince() { // 页面加载时，获取省份数据,给默认值
      getAction(`/user/findCityByParentId.do?parentId=${1}`).then(res => {
        this.province = res.data
        getAction(`/user/findCityByParentId.do?parentId=${this.province[0].cid}`).then(res => {
          this.city = res.data
          getAction(`/user/findCityByParentId.do?parentId=${this.city[0].cid}`).then(res => {
            this.prefecture = res.data
            this.ruleForm.sheng = this.province[0].cid
            this.ruleForm.shi = this.city[0].cid
            this.ruleForm.qu = this.prefecture[0].cid
          })
        })
      })
    },
    getCity(data) { // 获取市数据
      getAction(`/user/findCityByParentId.do?parentId=${data}`).then(res => {
        this.city = res.data
        getAction(`/user/findCityByParentId.do?parentId=${data}`).then(res => {
          this.prefecture = res.data
          this.ruleForm.shi = this.city[0].cid
          this.ruleForm.qu = this.prefecture[0].cid
        })
      })
    },
    getPrefecture(data) { // 获取地区数据
      getAction(`/user/findCityByParentId.do?parentId=${data}`).then(res => {
        this.prefecture = res.data
        this.ruleForm.qu = this.prefecture[0].cid
      })
    },
    register() { // 注册
      if(this.isUsername&&this.isPhone) {
        postAction(`/user/register.do?sheng=${this.ruleForm.sheng}&shi=${this.ruleForm.shi}&qu=${this.ruleForm.qu}`, this.ruleForm).then(res => {
          if (res.code == 200) {
            this.$message.success('注册成功!')
            this.$router.push('/login')
          }
        })
      }else {
        this.$message.error('用户名或手机号重复!')
      }
    }
  }
}
</script>

<style scoped lang="scss">
.body {
  height: 100%;
  margin: 0;
  display: flex; /*将 body 设置为 Flexbox 容器*/
  justify-content: center; /*水平居中对齐*/
  align-items: center; /*垂直居中对齐*/
  background-image: url("../../image/Loginimg/register.jpg");
  background-size: cover;
}

.content {
  width: 650px; /* 设置宽度 */
  height: 150px; /* 设置高度 */
  margin-top: -500px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
